import styles from "./EditPost.module.css";
import React, { useState } from "react";
import { type Post, useUpdatePostMutation } from "../../app/services/posts";

const EditablePostName = ({
  name: initialName,
  onUpdate,
  isLoading = false,
}: {
  name: string;
  onUpdate: (name: string) => void;
  isLoading?: boolean;
}) => {
  const [name, setName] = useState(initialName);

  const handleChange = ({
    target: { value },
  }: React.ChangeEvent<HTMLInputElement>) => setName(value);

  const handleUpdate = () => onUpdate(name);

  return (
    <div className={styles.container}>
        <h2>更新一个post</h2>
      <input
        type="text"
        onChange={handleChange}
        value={name}
        disabled={isLoading}
      />
      <button onClick={handleUpdate}>Update</button>
    </div>
  );
};

export const EditPost = () => {
  const [updatePost, { isLoading: isUpdating }] = useUpdatePostMutation();
  const aPost: Post = { id: "post-0", name: "new update post-0" };
  return (
    <EditablePostName
      name={aPost.name}
      onUpdate={async (name) => { // name是形参
        try {
          await updatePost({id:aPost.id,name}).unwrap();
        } catch {
          // toast({
          //   title: 'An error occurred',
          //   description: "We couldn't save your changes, try again!",
          //   status: 'error',
          //   duration: 2000,
          //   isClosable: true,
          // })
          console.log("err");
        }
      }}
    />
  );
};
